﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.Pernix.Common.DataAccess;
using Com.Pernix.Component.Member.Models;
using NHibernate;
using NHibernate.Criterion;

namespace Com.Pernix.Component.Member.BL.Repositories
{
    public class UserRepository : IRepository<User>
    {
        private readonly IUnitOfWork _unitOfWork;

        public UserRepository(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }
        public User GetById(User objectkey)
        {
            return _unitOfWork.CurrentSession.Get<User>(objectkey.Username);
        }

        public IList<User> GetByUsernameStartWith(String username)
        {
            return _unitOfWork.CurrentSession.CreateCriteria<User>("xxx").Add(Restrictions.Like("Username", "%" + username + "%")).List<User>();

        }

        public void Add(User entity)
        {
            _unitOfWork.CurrentSession.SaveOrUpdate(entity);
        }

        public void Add(User entity, bool commit)
        {
            this.Add(entity);
            if (commit)
            {
                _unitOfWork.Commit();
            }
        }

        public void Remove(User entity)
        {
            _unitOfWork.CurrentSession.Delete(entity);
        }

        public void Dispose()
        {
            _unitOfWork.Dispose();
        }

        public void Commit()
        {
            _unitOfWork.Commit();
        }

        public bool VerifyUser(User userRequireVerify)
        {
            User userResult = this.GetById(userRequireVerify);
            if (userResult != null && userResult.Password.Equals(userRequireVerify.Password))
            {
                return true;
            }
            return false;
        }
    }
}
